import os
import platform
import setproctitle
from flask import send_file, render_template_string

from basic.config import GlobalCfg, GlobalInfo
from basic.workspace import Workspace
from basic.log import Log


class Module(object):
    """
    基类，表示提供某种服务的一个模块。
    """

    def __init__(self, parent, name, desc=None):
        # 父模块
        self.parent = parent
        # 模块名
        self.name = name
        # 模块描述
        self.desc = desc
        # 是否由单独进程来运行run函数。进程由调用者负责启动，不需要自己启动。
        self.independent = False
        # 模块代码目录
        self.program_path = os.path.join(parent.program_path, self.name) if parent is not None else \
                            os.path.dirname(os.path.abspath(__file__))
        # 模块工作目录、日志组件
        self.workspace = Workspace(parent.workspace if parent is not None else None, name)
        self.runlog = Log(self.workspace.path)

    def run(self):
        """
        模块运行接口，外部调用此接口，启动此模块的运行。
        """
        pass
    
    def enable(self):
        """
        外部调用此接口，获取子模块是否配置正确可以运行。
        """
        return True

    def setproctitle(self, title):
        if GlobalInfo.is_multi_process_mode:
            setproctitle.setproctitle(title)

    def builtin_file(self, *name):
        """
        获取内置文件路径
        """
        return os.path.join(self.program_path, *name)


class WebsiteRoute(object):
    """
    web路由链接
    """
    def __init__(self, name, url, hook, methods=['get'], desc=None):
        self.name = name
        self.url = url
        self.hook = hook
        self.methods = methods
        self.desc = desc


class WebsiteModule(Module):
    """
    基类，可以提供Web网页服务的模块。
    """
    def __init__(self, parent, name, desc='暂无描述'):
        super(WebsiteModule, self).__init__(parent, name, desc)
        self.url = f'{GlobalInfo.website_address}/{name}'
        self.routes = []
        self.add_routes(self.name, f'/{self.name}', self.homepage, desc=desc)

    def add_routes(self, name, url, hook, methods=['get'], desc=None):
        """
        添加一个网页路由
        """
        self.routes.append(WebsiteRoute(name, url, hook, methods, desc))
    
    def homepage(self):
        """
        默认主页
        """
        return f'<h>homepage of {self.name}</h>'
    
    def send_file(self, filename):
        return send_file(self.builtin_file(filename))

    def render_template(self, filename, **kwargs):
        with open(self.builtin_file(filename), 'r') as f:
            template = f.read()
        return render_template_string(template, **kwargs)
